package com.subtlman.logframework.utils;

import com.subtlman.logframework.queue.DealQueueThread;
import org.xml.sax.InputSource;

import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Create: IntelliJ IDEA.
 * @Author: subtlman_ljx
 * @Date: 2022/09/29/11:15
 * @Description: 工具类
 */
public class Util {

    /**
     * string转xml转XmlDate实体对象
     */
//    public static XmlData stringTransXml(String xmlStr) throws Exception{
//        StringReader sr = new StringReader(xmlStr);
//        InputSource is = new InputSource(sr);
//        Document document = (new SAXBuilder()).build(is);
//        Element element = document.getRootElement();
//        List<Element> contents = element.getContent();
//        Map map = new HashMap();
//        for (Element e:contents){
//            String name = e.getName();
//            List content = e.getContent();
//            String value = "";
//            if (!content.isEmpty()){
//                value = content.get(0).toString();
//                value = value.substring(7,value.length()-1);
//            }
//            map.put(name,value);
//        }
//        return mapToPOJO(map, XmlData.class);
//    }

    /**
     * 模拟定时器15分钟
     */
    public static void waitTime() throws InterruptedException{
        DealQueueThread myThread = new DealQueueThread();
        Thread thread = new Thread(myThread);
        thread.start();
    }

    /**
     * 移除换行\r、回车\n、制表\t符的字符串
     */
    public static String removeRNT(String originalStr) {
        if (originalStr == null || originalStr.isEmpty()) {
            return originalStr;
        }
        return originalStr.replaceAll("[\t\n\r]","");

    }

    /**
     * 例:map中有key为"id",value为"001"的数据,类对象为User,User中有Spring id;属性,
     * 返回值:返回User对象,你将获得一个id属性为"001"的User对象
     */
    public static <T> T mapToPOJO(Map map, Class clazz) throws Exception {
        //通过class对象拿到所有的字段(包括私有)
        Field[] declaredFields = clazz.getDeclaredFields();
        //通过class对象拿到实例对象,虽然此时它是Object类型
        Object newEntity = clazz.newInstance();
        //循环Field[]拿到每个属性对象
        for (Field field: declaredFields) {
            //打开属性对象的赋值权限
            field.setAccessible(true);
            if (map.get(field.getName()) != null){
                //然后通过map.get(field.getName())取到map里面的值field.set()进实例对象
                field.set(newEntity,map.get(field.getName()));
            }
        }
        //我们把Object转成泛型返回
        return (T) newEntity;
    }
}
